<?php
namespace app\cli\controller;

use \think\Controller;
use think\Request;
use think\Env;
use think\exception\HttpException;
class Soc extends Controller
{
    //获取配置
    public function get_socket_conf($attr=null)
    {
        $conf = array(
            "host" => Env::get("soc_host", "47.108.21.234"),//47.108.21.234
            "port" => 3315,
        );
        if(!empty($attr)){
            return $conf[$attr];
        }
        return $conf;
    }

    //发起请求
    public function index()
    {
        //if(Request::instance()->isAjax()){
        if(Request::instance()){
            $host = $this -> get_socket_conf("host");
            $port = $this -> get_socket_conf("port");
            //创建一个socket套接流
            $socket = socket_create(AF_INET,SOCK_STREAM,SOL_TCP);
            /****************设置socket连接选项，这两个步骤可以省略*************/
            //接收套接流的最大超时时间1秒，后面是微秒单位超时时间，设置为0，表示不管它
            socket_set_option($socket, SOL_SOCKET, SO_RCVTIMEO, array("sec" => 1, "usec" => 0));
            //发送套接流的最大超时时间为6秒
            socket_set_option($socket, SOL_SOCKET, SO_SNDTIMEO, array("sec" => 6, "usec" => 0));
            /****************设置socket连接选项，这两个步骤你可以省略*************/

            $result = "";
            //连接服务端的套接流，这一步就是使客户端与服务器端的套接流建立联系
            if(@socket_connect($socket, $host, $port) == false){
                $result = 'Server error:' . $this -> doEncoding(socket_strerror(socket_last_error()));
                //$result = "Error:unable to connect...";
            }else{
                $request = input('request.');
                //$message = "\{\"fun\":\"notice\",\"cont\":\"".$request["cont"]."\",\"worker\":\"".$request["worker"]."\"\}";
                $message = $this -> set_message($request);// 设置消息，仅适用于后台操作类
                if(empty($message)){// 设置消息，非后台操作类
                    $message = $request;
                    unset($message['/cli/soc']);// 剔除当前脚本的url
                    $message = arr_to_jsonstr($message);// 设置非操作类消息
                }
                record_log($message, "socket_msg");//记录日志
                //转为GBK编码，如果需要(用于处理乱码问题)
                //$message = mb_convert_encoding($message,'GBK','UTF-8');
                //向服务端写入字符串信息(将消息发送给服务器)
                if(socket_write($socket, $message, strlen($message)) == false){
                    echo 'Error:' . $this -> doEncoding(socket_strerror(socket_last_error()));
                }else{
                    //读取服务端返回来的套接流信息
                    while($callback = socket_read($socket, 1024)){
                        $result = $callback;//服务器返回消息，succ表示成功
                    }
                }
            }
            socket_close($socket);//工作完毕，关闭套接流
            return $result;//将结果返回给视图
        }
    }

    /**
     * 处理数据，设置操作类消息
     */
    public function set_message($msg=[])
    {
        $option = isset($msg["fun"]) ? $msg["fun"] : "";
        $message = "";
        switch ($option) {
            case 'email':
                $message = "{\"fun\":\"".$msg["fun"]."\",\"player\":\"".$msg["player"]."\",\"title\":\"".$msg["title"]."\",\"cont\":\"".$msg["cont"]."\",\"addit\":\"".$msg["addit"]."\",\"worker\":\"".$msg["worker"]."\"}";
                break;
            case 'notice':
                $message = "{\"fun\":\"".$msg["fun"]."\",\"cont\":\"".$msg["cont"]."\",\"worker\":\"".$msg["worker"]."\"}";
                break;
            case 'plaer_disable':
            case 'player_enable':
                $message = "{\"fun\":\"".$msg["fun"]."\",\"player\":\"".$msg["player"]."\"}";
                break;
            case 'xuan_mosaic':
                $message = "{\"fun\":\"".$msg["fun"]."\",\"nike\":\"".$msg["nike"]."\",\"pi\":\"".$msg["pi"]."\",\"px\":\"".$msg["px"]."\"}";
                break;
            case 'ext_execute':
                $message = "{\"fun\":\"".$msg["fun"]."\",\"order\":\"".$msg["order"]."\",\"option\":\"".$msg["option"]."\",\"worker\":\"".$msg["worker"]."\"}";
                break;
            case 'paid':
                $message = "{\"fun\":\"".$msg["fun"]."\",\"player\":\"".$msg["player"]."\",\"gold\":\"".$msg["gold"]."\",\"mark\":\"".$msg["mark"]."\",\"worker\":\"".$msg["worker"]."\"}";
                break;
            case 'full_start':
            case 'full_stop':
            case 'xuan_start':
            case 'xuan_stop':
            case 'pay_start':
            case 'pay_stop':
            case 'ext_start':
            case 'ext_stop':
                $message = "\{\"fun\":\"".$msg["fun"]."\"\}";
                break;
            default:break;
        }
        return $message;
    }

    /**
     * 处理乱码的错误信息(比如socket，tcp...)
     * @param $str
     * @return null|string|string[]
     */
    public function doEncoding($str){
        $encode = strtoupper(mb_detect_encoding($str, ["ASCII",'UTF-8',"GB2312","GBK",'BIG5']));
        if($encode != 'UTF-8'){
            $str = mb_convert_encoding($str, 'UTF-8', $encode);
        }
        return $str;
    }
}